package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.RegisterUserReq;
import net.ib.mntalk.protocol.Session.RegisterUserRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.ui.start.NameActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class RegisterUserTask extends AsyncNetTask {

	private RegisterUserReq mReq;
	
	public RegisterUserTask(Context context, Handler handler, RegisterUserReq req) {
		super(context, handler);
		mReq = req;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope revelop = new TcpEnvelope.Builder()
			.setMethodId(Session.Registration.RegisterUser)
			.setMessage(mReq)
			.setType(TcpEnvelope.REQUEST)
			.build();
		MTalkLogWriter.d("RegisterUserTask.onPreExecute()");
		return revelop;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		MTalkLogWriter.d("RegisterUserTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		RegisterUserRes res = (RegisterUserRes) resultEnvelope.getMessage();
		
		if(res.getResponseCode() == Common.SUCCESS){
			GlobalPreferences.setUserUUID(res.getUserToken().getUserUuid());
			if(mReq.getUserName() != null)
				GlobalPreferences.setUserName(mReq.getUserName().getFirstName());
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REGISTER_USER_SUCCESS);
			msg.obj = res.getUserToken();
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else{
			MTalkLogWriter.d(res.getResponseCode() + " RegisterUserTask");
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REGISTER_USER_FAIL));
		}
	}

}
